package com.ja.openchat.viewmodels;

import android.app.Application;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
import androidx.fragment.app.FragmentActivity;

import com.google.gson.JsonObject;
import com.ja.openchat.ui.contact.search.PublicSearchSectionAdapter;
import com.ja.openchat.ui.contact.search.SearchSection;
import com.ja.openchat.ui.contact.search.SearchSectionInfo;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.user.UserInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.utils.KLog;


public class ChatSearchPageViewModel extends BaseViewModel {

    private FragmentActivity activity;
    private ChatSearchViewModel chatSearchViewModel;
    private int position;
    public List<SearchSection> sectionList = new ArrayList<>();
    //好友
    private List<UserInfo> myContactsList = new ArrayList<>();
    //公开联系人
    private List<UserInfo> publicContactsList = new ArrayList<>();
    private int searchPublicContactsTaskId;
    //我的群组
    private List<ChatInfo> myGroupList = new ArrayList<>();
    //公开群组
    private List<ChatInfo> publicGroupList = new ArrayList<>();
    //我的频道
    private List<ChatInfo> myChannelList = new ArrayList<>();
    //公开频道
    private List<ChatInfo> publicChannelList = new ArrayList<>();
    //聊天记录
    private List<MessageInfo> historyMsgList = new ArrayList<>();
    private PublicSearchSectionAdapter publicSearchSectionAdapter;

    public ChatSearchPageViewModel(@NonNull Application application) {
        super(application);
    }

    private ObservableList<MultiItemViewModel> totalData = new ObservableArrayList<>();

    public void setPosition(int position) {
        this.position = position;
    }

    public void doSearch(int position) {
        this.position = position;
        String keyword = chatSearchViewModel.search.get();
        KLog.d("keyword==" + keyword);
        myContactsList.clear();
        historyMsgList.clear();
//        if (TextUtils.isEmpty(keyword)) {
//            if (!Common.isEmpty(totalData)) {
//                observableList.addAll(totalData);
//            }
//        } else {
//            if (!Common.isEmpty(totalData)) {
//                for (MultiItemViewModel dateInfo : totalData) {
//                    BlogUserDateInfo entity = ((MyFollowItemViewModel) dateInfo).entity.get();
//                    UserInfo userInfo = UserInfo.getUserInfo(entity.user_id);
//                    if (userInfo != null && !TextUtils.isEmpty(userInfo.displayName()) && userInfo.displayName().contains(keyword)) {
//                        observableList.add(dateInfo);
//                    }
//                }
//            }
//        }

        switch (position) {
            case 0:
                //搜索好友
                List<UserInfo> list = TelegramManager.getTelegramManager().getTgData().getMyContacts(keyword);
                if (list.size() > 0) {
                    myContactsList.addAll(list);
                }
                reloadListUI(position);
                break;
            case 1:
                //搜索公开联系人、公开讨论组、公开频道
                if (!TextUtils.isEmpty(keyword)) {
                    TelegramManager.getTelegramManager().searchMyChatsList(getApplication(), keyword, new TgResultBlock<List<Long>>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, List<Long> chatIds) {
                            initSearchResult(chatIds, false, 1);
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {

                        }
                    });
                    TelegramManager.getTelegramManager().searchPublicChatsList(getApplication(), keyword, new TgResultBlock<List<Long>>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, List<Long> chatIds) {
                            initSearchResult(chatIds, true, 1);
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {

                        }
                    });
                }
                break;
            case 2:
                //搜索历史记录
                if (!TextUtils.isEmpty(keyword)) {
                    TelegramManager.getTelegramManager().searchMessagesList(activity, keyword, new TgResultBlock<List<MessageInfo>>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, List<MessageInfo> obj) {
                            if (obj != null && obj.size() > 0) {
                                historyMsgList.addAll(obj);
                            }
                            reloadListUI(position);
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {

                        }
                    });
                }
                break;
        }
    }


    private void initSearchResult(List<Long> chatIds, boolean isPublic, int positon) {
        if (chatIds != null && chatIds.size() > 0) {
            HashMap<Long, ChatInfo> hashMap = new HashMap<>();
            for (long chatId : chatIds) {
                TelegramManager.getTelegramManager().requestChatInfoByChatId(getApplication(), chatId, new TgResultBlock<ChatInfo>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                        hashMap.put(chatId, obj);
                        publicGroupList.clear();
                        List<ChatInfo> chatInfos = new ArrayList<>();
                        if (hashMap != null && hashMap.size() > 0) {
                            for (Long o : hashMap.keySet()) {
                                ChatInfo fullInfo = hashMap.get(o);
                                if (fullInfo != null && fullInfo.isSuperGroup()) {
                                    fullInfo.isMine = !isPublic;
                                    chatInfos.add(fullInfo);
                                }
                            }
                        }
                        publicGroupList.addAll(chatInfos);
                        reloadListUI(positon);
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {

                    }
                });
            }
        } else {
            reloadListUI(positon);
        }
    }

    //"好友", "公开联系人", "我的群组", "公开群组", "我的频道", "公开频道", "聊天记录"
    private void reloadListUI(int position) {
        sectionList.clear();
        if (myContactsList.size() > 0 && position == 0) {//好友
            sectionList.add(new SearchSection(true, new SearchSectionInfo(""), SearchSection.SearchSectionType_MyContacts));
            for (UserInfo user : myContactsList) {
                sectionList.add(new SearchSection(false, user, SearchSection.SearchSectionType_MyContacts));
            }
        }
        if (publicGroupList.size() > 0 && position == 1) {//群组
            sectionList.add(new SearchSection(true, new SearchSectionInfo(""), SearchSection.SearchSectionType_PublicContacts));
            for (ChatInfo chatInfo : publicGroupList) {
                sectionList.add(new SearchSection(false, chatInfo, SearchSection.SearchSectionType_PublicContacts));
            }
        }
        if (historyMsgList.size() > 0 && position == 2) {//聊天记录
            sectionList.add(new SearchSection(true, new SearchSectionInfo(""), SearchSection.SearchSectionType_HisMsgs));
            for (MessageInfo msg : historyMsgList) {
                sectionList.add(new SearchSection(false, msg, SearchSection.SearchSectionType_HisMsgs));
            }
        }
        publicSearchSectionAdapter.notifyDataSetChanged();
    }

    public void setData(Bundle bundle) {
        if (bundle != null) {
        }
    }

    public void setActivity(FragmentActivity activity) {
        this.activity = activity;
    }

    public void setChatSearchViewModel(ChatSearchViewModel chatSearchViewModel) {
        this.chatSearchViewModel = chatSearchViewModel;
    }

    public void setAdapter(PublicSearchSectionAdapter publicSearchSectionAdapter) {
        this.publicSearchSectionAdapter = publicSearchSectionAdapter;
    }
}
